﻿

//used for the jquery block plugin
var loadingImage = $('<div/>', {
    "css": { 
        "background-image":"url(../../Resources/Images/LoadingGifs/ThreeBarBlue.gif)",
        "background-repeat":"no-repeat",
        "background-position":"center",
        "z-index":"2100"
    }
})[0];

var _miniProcessingOptions = {
    baseZ: 2000,
    //    centerX: true,
    //    centerY:true,
    css: {
        border: "1px solid #aaa"
    },
    message: "Loading", //$('<img/>', {
//        "src": document.location.protocol + "//" + document.location.host + "/Resources/Images/LoadingGifs/ThreeBarBlue.gif"
//    }),
    overlayCSS: {
        backgroundColor: '#FFF',
        opacity: 0.8
    },
    onBlock: function () {
        //stupid thing doesn't center properly on inital load
//        $(this).css("position", "absolute");
//        $(this).css("top", (($(this).parent().height() - $(this).outerHeight()) / 2) + $(this).parent().scrollTop() + "px");
//        $(this).css("left", (($(this).parent().width() - $(this).outerWidth()) / 2) + $(this).parent().scrollLeft() + "px");
    }
}

//#############################################################
//## Begin processing functions                              ##
//#############################################################

// Changes the mouse cursor to processing
function ShowProcessingCursor() {
    document.body.style.cursor = 'wait';
}

// Changes the mouse cursor back to normal
function HideProcessingCursor() {
    document.body.style.cursor = 'default';
}

// Hides the content div and shows the processing div
function ShowProcessing() {
    if (typeof CloseAllMenuItems == 'function') { CloseAllMenuItems(true); }
    
    if (document.getElementById("content")) {
        // getElementByID() is the preffered way to access page variables (but it doesn't work in all instances, that's why there an else if)
        document.getElementById("content").style.display = "none";
        document.getElementById("processing").style.display = "inline";
    }
    else if (document.all) {
        // old versions of msie support document.all instead of getElementByID()
        document.all["content"].style.display = "none";
        document.all["processing"].style.display = "inline";
    }
    else if (document.layers) {
        // and some browsers only support layers (nn4)
        document.layers["content"].display = "none";
        document.layers["processing"].display = "";
    }
    window.scroll(0, 0);

    // kick the animated gif because it doesn't animate sometimes in IE
    setTimeout('document.images["processingGif"].src = "/Resources/Images/LoadingGifs/ProgressBarGold.gif"', 45);

    if (typeof ToggleStatuses == 'function') { ToggleStatuses(true); }
    if ($("#toolbarContent input").length > 0) {
        $("#toolbarContent").hide();
    }
}

// Hides the processing div and shows the content div
function HideProcessing() {
    if (document.getElementById("content")) {
        // getElementByID() is the preffered way to access page variables (but it doesn't work in all instances, that's why there an else if)
        document.getElementById("processing").style.display = "none";
        document.getElementById("content").style.display = "inline";
    }
    else if (document.all) {
        // old versions of msie support document.all instead of getElementByID()
        document.all["processing"].style.display = "none";
        document.all["content"].style.display = "inline";
    }
    else if (document.layers) {
        // and some browsers only support layers (nn4)
        document.layers["processing"].display = "none";
        document.layers["content"].display = "inline";
    }
    window.scroll(0, 0);
    if ($("#toolbarContent input").length > 0) {
        $("#toolbarContent").show();
    }
}

//#############################################################
//## End processing functions                                ##
//#############################################################

//#############################################################
//## Begin top menu functions                                ##
//#############################################################

var tmTimeout = 500; // the number of milliseconds a menu drop down will stay open
var tmCloseTimer = 0;
var tmMenuItem = 0; // the currently opened menu drop down

// Opens one of the menu drop downs in the top menu
// id: The id of the menu drop down to open
function OpenTopMenu(id) {
    // cancel close timer
    CancelTopMenuCloseTimer();

    // close the previously opened drop down
    if (tmMenuItem) tmMenuItem.style.display = 'none';

    // get the menu drop down and show it
    tmMenuItem = document.getElementById(id);
    tmMenuItem.style.display = '';

    $("#bodyContent").css("z-index", "1");
}
// close showed layer
function CloseTopMenu() {
    if (tmMenuItem) tmMenuItem.style.display = 'none';
}

// go close timer
function SetTopMenuCloseTimer() {
    tmCloseTimer = window.setTimeout(CloseTopMenu, tmTimeout);
}

// cancel close timer
function CancelTopMenuCloseTimer() {
    if (tmCloseTimer) {
        window.clearTimeout(tmCloseTimer);
        tmCloseTimer = null;
    }
}

// close the currently opened menu if the user clicks anywhere on the page
//document.onclick = CloseTopMenu;

//#############################################################
//## End top menu functions                                  ##
//#############################################################


$(function () {
    if ($.cookies !== undefined) {
        setPageScroll();

        //unset cookie after setting scroll position
        $.cookies.del('scrollPosition');
    }

    $("#bodyContent").scroll(function () {
        $.cookies.set('scrollPosition', null);
    });

    var existingBeforeUnload = window.onbeforeunload;
    window.onbeforeunload = function (event) {
        if (existingBeforeUnload) existingBeforeUnload(event);

        var logoffRequest = {
            "FuntionName": "Logoff"
        };

        var logoffResponse = function (jsonResponse) {
            //shouldn't need to do anything
        };

        var logoffRequestManager = new RequestManager(logoffRequest, logoffResponse, true);
        //logoffRequestManager.ExecuteRequest();
    }
});

function goToScroll() {
    if ($.cookies !== undefined) {
        var cookie = $.cookies.get('scrollPosition');

        if(cookie != null)
        {
            //set window scroll position if cookie is set
            $("#bodyContent").scrollTop(cookie);
        }
    }
}

function setPageScroll(targetTop) {
    if ($.cookies !== undefined) {
        $.cookies.set('scrollPosition', "\"" + getPageScroll(targetTop) + "\"");
    }
}


window.onbeforeunload = function () {
    setPageScroll();
};

//this function simply gets the window scroll position, works in all browsers
function getPageScroll(targetTop) {
    var yScroll;
    if (targetTop !== undefined) {
        yScroll = targetTop;
    } else if (self.pageYOffset) {
        yScroll = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
        yScroll = document.documentElement.scrollTop;
    } else if (document.body) {
        yScroll = document.body.scrollTop;
    }
    return yScroll
}


// scrolls to the bottom of the textarea handed in
// id: The id of the textarea in question
function ScrollToBottomOfTextarea(id) {

    try {
        txtArea = document.getElementById(id);
        txtArea.scrollTop = txtArea.scrollHeight - txtArea.clientHeight;
    }
    catch (ex) {
    }

}


// enable to set MaxLength on multiline texbox. ex. -- onkeypress="return TextboxMultilineMaxNumber(this,120)"
function TextboxMultilineMaxNumber(txt, maxLen) {
    try {
        if (txt.value.length > (maxLen - 1))

            return false;
    } catch (e) {
    }
}

// this is used by PrivatePages.Master.  It helps keep the proper accordion pane opened between page hits.
function SetSelectedMenuPane(paneID) {

    // note that we are using cookies because we need to get the paneID to the next page hit.  A hidden variable won't cut it because it won't survive to the next page even if it is one the master page.

    document.cookie = "curMenuAccPane=" + paneID + "; path=/";

}

(function ($) {
    $.fn.hasScrollBar = function () {
        if(typeof this.get(0) != 'undefined')
        {
            return this.get(0).scrollHeight > $(this.get(0).parentElement).height();
        }
    }
})(jQuery);

(function ($) {
    
    var options = {
    "selectionChanged":function(selectedItemId){},
    "selectedValue":null};

    $.fn.selectable = function (options) {
        if(typeof this.get(0) != 'undefined')
        {
            $(this).addClass("Selectable");
            var hiddenId = $(this)[0].id + "Hidden";
            $(this).children("li").each(function () {
                $(this).on("click", function () {                    
                    $(this).parent().children("li").removeClass("SelectedItem");
                    $(this).addClass("SelectedItem");
                    
                    $("#" + hiddenId).val(this.id);
                    if($("#" + hiddenId).attr("loading") !== "undefined" && $("#" + hiddenId).attr("loading") !== "true"){

                        if(typeof options.selectionChanged != "undefined")
                        {
                            options.selectionChanged(this.id);
                        }                    
                    }
                   else {
                        $("#" + hiddenId).removeAttr("loading");
                    }
                })
                .on("mouseover", function () {
                    $(this).addClass("SelectItem");
                })
                .on("mouseout", function () {
                    $(this).removeClass("SelectItem");
                });
            });              
        
            if(typeof options.selectedValue != "undefined" && options.selectedValue != null)
            {
                $(this).children("#" + options.selectedValue).addClass("SelectedItem");
            } 
                
            var hiddenControl = $("<input>")
                .attr({"type":"hidden", "id": hiddenId, "value":options.selectedValue})
                .on("change", function(){
                        if($("#" + $(this).val()).length > 0){
                            $("#" + $(this).val()).click();
                        }
                    
                });

            $(this).parent().append(hiddenControl);
        }
    }
})(jQuery);

String.prototype.format = String.prototype.f = function() {
    var s = this,
        i = arguments.length;

    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    }
    return s;
};


String.prototype.htmlEscape = function () {
    return String(this)
            //.replace(/&/g, '\&')
            .replace(/"/g, '\\"')
            .replace(/'/g, "\'")
            //.replace(/;/g, '&#50;')
//            .replace(/</g, '&lt;')
//            .replace(/>/g, '&gt;')
            .replace(/\n/g, '\\n');
}